import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginRequest, RegisterRequest } from '@/types'
import { apiService } from '@/services/api'
import { signalRService } from '@/services/signalr'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const isOnline = computed(() => user.value?.isOnline || false)

  // 初始化 - 从本地存储恢复状态
  const initialize = async () => {
    const savedToken = localStorage.getItem('auth_token')
    const savedUser = localStorage.getItem('user_info')

    if (savedToken && savedUser) {
      token.value = savedToken
      try {
        user.value = JSON.parse(savedUser)

        // 页面刷新后重新建立 SignalR 连接
        try {
          await signalRService.connect(savedToken)
          console.log('页面刷新后 SignalR 重连成功')
          // 更新用户在线状态
          updateOnlineStatus(true)
        } catch (error) {
          console.error('页面刷新后 SignalR 重连失败:', error)
          // 如果 SignalR 连接失败，可能是 token 过期，清除认证信息
          clearAuth()
        }
      } catch (e) {
        console.error('解析用户信息失败:', e)
        clearAuth()
      }
    }
  }

  // 登录
  const login = async (credentials: LoginRequest) => {
    isLoading.value = true
    error.value = null

    try {
      const response = await apiService.login(credentials)
      
      token.value = response.token
      user.value = response.user

      // 保存到本地存储
      localStorage.setItem('auth_token', response.token)
      localStorage.setItem('user_info', JSON.stringify(response.user))

      // 建立 SignalR 连接
      await signalRService.connect(response.token)

      // 更新用户在线状态
      updateOnlineStatus(true)

      return response
    } catch (err: any) {
      error.value = err.response?.data?.message || '登录失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  const register = async (userData: RegisterRequest) => {
    isLoading.value = true
    error.value = null

    try {
      const response = await apiService.register(userData)
      
      token.value = response.token
      user.value = response.user

      // 保存到本地存储
      localStorage.setItem('auth_token', response.token)
      localStorage.setItem('user_info', JSON.stringify(response.user))

      // 建立 SignalR 连接
      await signalRService.connect(response.token)

      // 更新用户在线状态
      updateOnlineStatus(true)

      return response
    } catch (err: any) {
      error.value = err.response?.data?.message || '注册失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = async () => {
    isLoading.value = true

    try {
      // 断开 SignalR 连接
      await signalRService.disconnect()
      
      // 调用后端登出接口
      if (token.value) {
        await apiService.logout()
      }
    } catch (err) {
      console.error('登出请求失败:', err)
    } finally {
      clearAuth()
      isLoading.value = false
    }
  }

  // 清除认证信息
  const clearAuth = () => {
    user.value = null
    token.value = null
    error.value = null
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_info')
    // 断开 SignalR 连接
    signalRService.disconnect()
  }

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    if (!token.value) return

    try {
      const userData = await apiService.getCurrentUser()
      user.value = userData
      localStorage.setItem('user_info', JSON.stringify(userData))
    } catch (err: any) {
      console.error('获取用户信息失败:', err)
      if (err.response?.status === 401) {
        clearAuth()
      }
    }
  }

  // 更新用户信息
  const updateUser = async (userData: Partial<User>) => {
    if (!user.value) return

    try {
      const updatedUser = await apiService.updateCurrentUser(userData)
      user.value = updatedUser
      localStorage.setItem('user_info', JSON.stringify(updatedUser))
      return updatedUser
    } catch (err: any) {
      error.value = err.response?.data?.message || '更新用户信息失败'
      throw err
    }
  }

  // 修改密码
  const changePassword = async (currentPassword: string, newPassword: string) => {
    try {
      await apiService.changePassword({ currentPassword, newPassword })
    } catch (err: any) {
      error.value = err.response?.data?.message || '修改密码失败'
      throw err
    }
  }

  // 更新在线状态
  const updateOnlineStatus = (isOnline: boolean) => {
    if (user.value) {
      user.value.isOnline = isOnline
      localStorage.setItem('user_info', JSON.stringify(user.value))
    }
  }

  // 搜索用户
  const searchUsers = async (searchTerm: string) => {
    try {
      return await apiService.searchUsers(searchTerm)
    } catch (err: any) {
      error.value = err.response?.data?.message || '搜索用户失败'
      throw err
    }
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 初始化
  initialize()

  return {
    // 状态
    user,
    token,
    isLoading,
    error,
    
    // 计算属性
    isAuthenticated,
    isOnline,
    
    // 方法
    login,
    register,
    logout,
    clearAuth,
    fetchCurrentUser,
    updateUser,
    changePassword,
    updateOnlineStatus,
    searchUsers,
    clearError
  }
})
